#!/usr/bin/env python3
"""
Python Streamable-HTTP MCP 天气服务器
"""
import os
import json
import asyncio
from typing import Any, Dict

import httpx
from dotenv import load_dotenv
from fastmcp import FastMCP

# --------------------------
# 1. 环境变量
# --------------------------
load_dotenv()
API_KEY = os.getenv("API_KEY")
PORT = int(os.getenv("PORT", 4000))

if not API_KEY:
    raise RuntimeError("请在 .env 中配置 API_KEY，例如：\nAPI_KEY=你的KEY\nPORT=4000")

# --------------------------
# 2. 创建 MCP 实例
# --------------------------
mcp = FastMCP("weather-mcp-http")

# --------------------------
# 3. 工具定义
# --------------------------
@mcp.tool()
async def get_weather(city: str) -> str:
    """
    获取指定城市实时天气
    :param city: 城市名称，如 北京
    """
    url = "http://apis.juhe.cn/simpleWeather/query"
    params = {"key": API_KEY, "city": city}

    async with httpx.AsyncClient(timeout=10) as client:
        resp = await client.get(url, params=params)
        if resp.status_code != 200:
            raise RuntimeError(f"接口返回 {resp.status_code}")

    data = resp.json()
    return json.dumps(data, ensure_ascii=False, indent=2)

# --------------------------
# 4. 启动
# --------------------------
if __name__ == "__main__":
    mcp.run(transport="http", host="0.0.0.0", port=PORT)